import pymysql

from testproj.baseutil import FileRead


def connect(db):
    conn = None
    try:
        conn = pymysql.connect(user=db["user"],
                               password=db["pwd"],
                               host=db["host"],
                               database=db["dbname"],
                               port=int(db["port"]),
                               charset="utf8")
        print("连接成功")
    except Exception as e:
        print(f"连接数据库异常{e}")
    return conn


def db_close(conn):
    try:
        conn.close()
    except Exception as e:
        print(e)


def execute(conn, sql):
    cursor = None
    try:
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()
    except Exception as e:
        print(f"连接数据库异常{e}")
    finally:
        cursor.close()


def executeQuery(conn, sql):
    cursor = None
    try:
        cursor = conn.cursor()
        cursor.execute(sql)
        return cursor.fetchall()
    except Exception as e:
        print(f"连接数据库异常{e}")
    finally:
        cursor.close()

def deleteById(conn, mobilephone):
    sql = f"delete from member where mobilephone = '{mobilephone}'"
    execute(conn,sql)

def selectByPhone(conn, mobilephone):
    sql = f"select * from member where mobilephone = '{mobilephone}'"
    cursor = None
    try:
        cursor = conn.cursor()
        cursor.execute(sql)
        return cursor.fetchone()
    except Exception as e:
        print(f"连接数据库异常{e}")
    finally:
        cursor.close()



if __name__ == '__main__':
    db = eval(FileRead.read_ini("data_env/env.ini", "db"))
    conn = connect(db)
    # sql = "select * from member"
    print(selectByPhone(conn, "111111"))
    # deleteById(conn,'18291363298')
